import dayjs, { Dayjs } from "dayjs";
import isoWeek from "dayjs/plugin/isoWeek";
import quarter from "dayjs/plugin/quarterOfYear";
import customParseFormat from "dayjs/plugin/customParseFormat";
import minMax from "dayjs/plugin/minMax";
import type { TaskMode } from "../types";
import { getTimeUnitWidth } from "./utils";

dayjs.extend(isoWeek);
dayjs.extend(quarter);
dayjs.extend(customParseFormat);
dayjs.extend(minMax);

export function splitDateRange(start: Dayjs, end: Dayjs, taskMode: TaskMode) {
    const startDate = dayjs(start);
    let endDate = dayjs(end);
    switch (taskMode) {
        case "Week":
            endDate = dayjs(end).endOf('isoWeek');
            break;
        case "Month":
            endDate = dayjs(end).endOf('month');
            break;
        case "Quarter":
            endDate = dayjs(end).endOf('quarter');
            break;
        case "Year":
            endDate = dayjs(end).endOf('year');
            break;
        default:
            endDate = dayjs(end);
            break;
    }
    const segments = [];
    let current = startDate;

    while (current <= endDate) {
        switch (taskMode) {
            case "Day":
                segments.push(current.format('YYYY-MM-DD'));
                current = current.add(1, 'day');
                break
            case "Week":
                segments.push([current.startOf('isoWeek').format('YYYY-MM-DD'), current.endOf('isoWeek').format('YYYY-MM-DD')]);
                current = current.add(1, 'week');
                break
            case "Month":
                segments.push([current.startOf('month').format('YYYY-MM-DD'), current.endOf('month').format('YYYY-MM-DD')]);
                current = current.add(1, 'month');
                break
            case "Quarter":
                segments.push([current.startOf('quarter').format('YYYY-MM-DD'), current.endOf('quarter').format('YYYY-MM-DD')]);
                current = current.add(1, 'quarter');
                break
            case "Year":
                segments.push([current.startOf('year').format('YYYY-MM-DD'), current.endOf('year').format('YYYY-MM-DD')]);
                current = current.add(1, 'year');
                break
        }
    }
    return segments;
}

export function getTotalWidth(tasksStart: Dayjs, tasksEnd: Dayjs, taskMode: TaskMode): number {
    const range = splitDateRange(tasksStart, tasksEnd, taskMode);
    if (taskMode === "Day") {
        return range.length * getTimeUnitWidth(taskMode);
    } else {
        let totalWidth = 0;
        range.forEach(item => {
            totalWidth += (dayjs(item[1]).diff(dayjs(item[0]), "day") + 1) * getTimeUnitWidth(taskMode);
        });
        return totalWidth;
    }
}
